#include "getsDispose.h"

void mmapTransfileGet(int fd,int sockfd,int filesize){
    ftruncate(fd,filesize);
    char * p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    send(sockfd,p,filesize,MSG_NOSIGNAL);
    munmap(p,filesize);
    return ;
}

void trainTransfileGets(int fd,int sockfd){
    Train train;
    char buf[1024];
    while(1){
        bzero(buf,sizeof(buf));
        int rret = read(fd,buf,sizeof(buf));
        if(rret == 0){
            train.length = 0;
            send(sockfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
            break;
        }
        train.length = rret;
        memcpy(train.data,buf,train.length);
        send(sockfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
    }
    return ;
}


void getsDispose(int netfd,char * username,MYSQL * mysql,char * prev_path,char * real_path){
   
     
    char sql[1024] = {0};              //检查一下,有没有这个文件
    sprintf(sql,"select * from usrfile where username = '%s' and path = '%s' ;",username,prev_path);
    int qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"mysql_query 1:%s\n",mysql_error(mysql));
        send(netfd,"0",1,MSG_NOSIGNAL);
        return ;
    }
    printf("prev_path:%s\n",prev_path);
    printf("1 over\n");
    MYSQL_RES * table = mysql_store_result(mysql);
    
    if(mysql_num_rows(table) == 0){
        send(netfd,"0",1,MSG_NOSIGNAL);
        return ;
    }

    MYSQL_ROW row1 = mysql_fetch_row(table);     //记录一下父节点
    
    if( strcmp(row1[5],"d") == 0){
        send(netfd,"0",1,MSG_NOSIGNAL);
        return ;
    }else{
        send(netfd,"1",1,MSG_NOSIGNAL);
    } 
    char real_file_path[1024] = {0};
    char real_name [1024] = {0};
    char xiegang[] = "/";
    memcpy(real_file_path,real_path,strlen(real_path));
    memcpy(real_name,row1[6],strlen(row1[6]));
    strcat(real_file_path,xiegang);
    strcat(real_file_path,real_name);
    Train train;
    printf("real_file_path:%s\n",real_file_path);
    int fd = open(real_file_path,O_RDWR);
    struct stat statbuf;
    fstat(fd,&statbuf);
    char isBig ;
    if(statbuf.st_size > 104857600){
        isBig = '1';
    }else{
        isBig = '0';
    }
    send(netfd,&isBig,1,MSG_NOSIGNAL);
    train.length = sizeof(statbuf.st_size);
    memcpy(train.data,&statbuf.st_size,train.length);
    send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
    if(isBig == '1'){
        mmapTransfileGet(fd,netfd,statbuf.st_size);
    }
    if(isBig == '0'){
        trainTransfileGets(fd,netfd);
    }

    return ;
}


